package net.wantongtech.xa.uploadbasicinfo.dao;

import com.google.common.collect.Lists;
import com.wtkj.dao.impl.BaseDataTemplate;
import net.wantongtech.xa.uploadbasicinfo.vo.DfsFileEntry;
import org.apache.commons.lang3.Validate;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * 扫描删除DFS文件DAO
 *
 * @author MaShibo
 * 2021/1/13 0013
 */
@Repository
public class ScanFastDFSDao extends BaseDataTemplate {


    public Integer queryTotalCnt(Date maxModifyTime) {
        Validate.notNull(maxModifyTime);
        final String sql = "select count(1) from tmp_dfs_file a where a.modifytime < ? ";
        return jdbcTemplate.queryForObject(sql, Integer.class, maxModifyTime);
    }

    public Integer updateDeleteFlag(Integer id) {
        final String sql = "UPDATE tmp_dfs_file a SET a.delflag = ? WHERE a.id = ?";
        return jdbcTemplate.update(sql, DfsFileEntry.DEL_FLAG_DONE, id);
    }


    public List<DfsFileEntry> queryDfsFileEntriesByRowAndModifyTime(int start, int end, Date maxModifyTime) {
        final String sql =
                "select *\n" +
                        "  from (select a.*, rownum as rm\n" +
                        "          from tmp_dfs_file a\n" +
                        "         where a.modifytime < ?\n" +
                        "           and rownum <= ?)\n" +
                        " where rm >= ?";
        return jdbcTemplate.query(sql, rs -> {
            List<DfsFileEntry> dfsFileEntryList = Lists.newArrayList();
            while (rs.next()) {
                int id = rs.getInt(1);
                String path = rs.getString(2);
                Date modifyTime = (Date) JdbcUtils.getResultSetValue(rs, 3, Date.class);
                long fileSize = rs.getLong(4);
                DfsFileEntry dfsFileEntry = new DfsFileEntry(id, path, modifyTime,
                        fileSize, DfsFileEntry.DEL_FLAG_NONE);
                dfsFileEntryList.add(dfsFileEntry);
            }
            return dfsFileEntryList;
        }, maxModifyTime, end, start);
    }


}
